﻿using System;
using System.Linq;
using System.Threading.Tasks;
using VisionCloud.Domain.DtoModel.Sys;
using VisionCloud.Domain.Repository.Interface.Sys;

namespace VisionCloud.Service.Sys
{
    public class NotificationService
    {
        public ISysNotificationRepository SysNotificationRepository { get; set; }

        public ISysNotifyUserRepository SysNotifyUserRepository { get; set; }

        /// <summary>
        /// 获取通知消息内容
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="isPrivate">是否是私有的，默认为否</param>
        /// <returns></returns>
        public async Task<SysNotificationDto> GetNotification(Guid userId, bool isPrivate = false)
        {
            SysNotificationDto notificationContent = new SysNotificationDto();
            var notifications = await SysNotificationRepository.WhereAsync(x => !x.IsDeleted
                                                                           && x.IsPrivate == isPrivate
                                                                           && x.CreatedDate > DateTime.Today.AddDays(-x.KeepDays));
            var updateNotification = notifications?.FirstOrDefault(x => (int)x.MessageType == 0);
            if (updateNotification != null)
            {
                notificationContent.UpdateNotificationId = updateNotification.Id;
                notificationContent.UpdateTitle = updateNotification.Title;
                notificationContent.UpdateContent = updateNotification.MessageContent;
                notificationContent.IsReaded = await SysNotifyUserRepository.AnyAsync(x => x.UserId == userId
                                                                                        && x.NotificationId == updateNotification.Id
                                                                                        && !x.IsExpired
                                                                                        && x.IsReaded);
            }
            var tipsNotification = notifications?.FirstOrDefault(x => (int)x.MessageType == 1);
            notificationContent.TipsContent = tipsNotification?.MessageContent;
            if (updateNotification == null)
            {
                //如果没有更新提示消息，则返回已读
                notificationContent.IsReaded = true;
            }
            return notificationContent;
        }


        public async Task<bool> SetReaded(Guid notificationId, Guid userId)
        {
            return await SysNotifyUserRepository.SetReaded(userId, notificationId);
        }
    }
}
